package com.example.demo.excel;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.example.demo.pdf.PDFDataTest;
import com.example.demo.pdf.PDFTemplateUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: HLB
 * @desc:
 * @version: V1.0.0
 */

@RestController
public class ExcelController {

    @RequestMapping(value="test")
    @ResponseBody
    public String exportExcelTest(HttpServletResponse response) throws IOException, URISyntaxException {
        // 获取workbook对象
        Workbook workbook = exportPicture() ;
        // 判断数据
        if(workbook == null) {
            return "fail";
        }
        // 设置excel的文件名称
        String excelName = "测试excel" ;
        // 重置响应对象
        response.reset();
        // 当前日期，用于导出文件名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = "["+excelName+"-"+sdf.format(new Date())+"]";
        // 指定下载的文件名--设置响应头
        response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xls");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 写出数据输出流到页面
        try {
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    public Workbook exportPicture() throws IOException, URISyntaxException {
        // 模板已经存放在项目的resources 包下
        TemplateExportParams params = new TemplateExportParams("D:\\dev\\code\\demo\\src\\main\\resources\\exceltemplates\\purchaseLog.xlsx");
        // 数据列表
        // 创建数据对象
        Map<String, Object> temp = getData();
        // 创建图片
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        // 网络图片
//        BufferedImage bufferImg = ImageIO.read(new URL("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2.zxxk.com%2F2015-4%2FZXXKCOM201504011711435794285.jpg&refer=http%3A%2F%2Fimg2.zxxk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1621074995&t=4a54f70fcb143e74aa25dc8515bfb917"));
        // 本地图片
        BufferedImage bufferImg = ImageIO.read(new File("D:/dev/code/demo/src/main/resources/images/MyQRCode.png"));
        ImageIO.write(bufferImg, "png", byteArrayOut);
        ImageEntity imageEntity = new ImageEntity(byteArrayOut.toByteArray(), 800, 1000);
        temp.put("imgUrl", imageEntity);
        Workbook book = ExcelExportUtil.exportExcel(params, temp);
        return book ;
    }

    private Map<String, Object> getData() {
        // 模板中的数据，实际运用从数据库中查询
        Map<String,Object> data = new HashMap<>();
        data.put("tobaccoStationName", "asdfasdf");
        data.put("tobaccoPurchaseName", "asdfasdf");
        data.put("growerName", "张三");
        data.put("identityCard", "123124124123123");
        data.put("growerAddress", "北航上号");
        data.put("imgUrl", "images/MyQRCode.png");
        data.put("totalWeight", "3300");
        data.put("totalMoney", "2000");
        data.put("userName", "粘钩");
        data.put("now", "2020-12-12");
        data.put("purData", "2020-12-12");
        data.put("plu", "2020");


        List<PDFDataTest> detailList = new ArrayList<>();
        detailList.add(new PDFDataTest("123456","测试","测试","测试","测试"));
        detailList.add(new PDFDataTest("111111","测试","测试","测试","测试"));
        detailList.add(new PDFDataTest("222222","测试","测试","测试","测试"));
        data.put("detailList", detailList);
        return data;
    }
}
